/**
 * common
 */

 
layui.define(function(exports){
  var $ = layui.$
  ,layer = layui.layer
  ,laytpl = layui.laytpl
  ,setter = layui.setter
  ,view = layui.view
  ,admin = layui.admin
  
  //公共业务的逻辑处理可以写在此处，切换任何页面都会执行
    //……
    var templateHelper = {
        genTmpl1(payload) {
            function getFlightRoutes() {
                const result = []
                for (let i = 0; i < 4; i++) {
                    const flight = payload.flightList[i]

                    if (flight) {
                        if (i === 0) {
                            result.push({ text: flight.from })
                            result.push({ text: flight.to })
                        } else {
                            result.push({ text: flight.from })
                        }
                    } else {
                        result.push({ text: '' })
                    }
                }

                return result
            }

            payload.routes = getFlightRoutes();
            //console.log(payload.routes);

            const html = layui.laytpl(`
    <div class="invoice-layout__wrap tmpl-1">
      <div class="invoice-layout__header">
        <h3 class="title">{{= d.title }}</h3>
        <div class="invoice-layout__header-content clearfix">
          <p class="fl">国内国际标识：<span class="value">{{= d.internationalFlag }}</span></p>
          <div class="fr">
            <p style="margin-bottom: 20px;">开票状态：<span class="value">{{= d.issuingStatusName }}</span></p>
            <p>发票号码：<span class="value">{{= d.invoiceNumber }}</span></p>
          </div>
        </div>
      </div>

      <table class="invoice-layout__table">
        <tr>
          <td>
            <p class="label">旅客姓名</p>
            <span class="value">{{= d.passengerName }}</span>
          </td>
          <td colspan="5">
            <p class="label">有效身份证件号码</p>
            <span class="value">{{= d.idNo }}</span>
          </td>
          <td colspan="4">
            <p class="label">签注</p>
            <span class="value">{{= d.restriction }}</span>
          </td>
        </tr>
        <tr>
          <th></th>
          <th width="80">承运人</th>
          <th>航班号</th>
          <th width="100">座位等级</th>
          <th width="80">日期</th>
          <th width="100">时间</th>
          <th width="140">客票级别/客票类别</th>
          <th width="100">客票生效日期</th>
          <th width="100">有效截止日期</th>
          <th width="80">免费行李</th>
        </tr>
        {{#  layui.each(d.flightList, function(index, item) { }}
          <tr>
            {{# if(index === 0) { }}
            <td rowspan="{{= d.flightList.length + 4 }}" width="200" class="vertical-top">
              {{#  layui.each(d.routes, function(idx, obj) { }}
                <p style="{{= idx !== d.routes.length -1 ? 'margin-bottom: 20px;' : '' }}">{{= idx === 0 ? '自' : '至' }}：<span class="value">{{= obj.text }}</span></p>
              {{#  }); }}
            </td>
            {{#  } }}
            <td class="vertical-top td-normal"><span class="value">{{= item.carrier }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.flightNumber }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.seatClass }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.flightDate }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.flightTime }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.fareBasis }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.客票生效日期 }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.有效截止日期 }}</span></td>
            <td class="vertical-top td-normal"><span class="value">{{= item.freeBaggage }}</span></td>
          </tr>
        {{#  }); }}
        {{#  layui.each([1, 2, 3], function(_, __) { }}
          <tr>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
            <td class="td-normal"></td>
          </tr>
        {{#  }); }}
        <tr>
          <td colspan="2">
            <p class="label">票价</p>
            <p class="text-right"><span class="value">CNY {{= d.fare }}</span></p>
          </td>
          <td>
            <p class="label">燃油附加费</p>
            <p class="text-right"><span class="value">CNY {{= d.fuelSurcharge }}</span></p>
          </td>
          <td>
            <p class="label">增值税税率</p>
            <p class="text-right"><span class="value">{{= d.taxRate }}</span></p>
          </td>
          <td>
            <p class="label">增值税税额</p>
            <p class="text-right"><span class="value">CNY {{= d.tax }}</span></p>
          </td>
          <td>
            <p class="label">民航发展基金</p>
            <p class="text-right"><span class="value">CNY {{= d.civilAviationFund }}</span></p>
          </td>
          <td>
            <p class="label">其他税费</p>
            <p class="text-right"><span class="value">CNY {{= d.otherTax }}</span></p>
          </td>
          <td colspan="2">
            <p class="label">合计</p>
            <p class="text-right"><span class="value">CNY {{= d.total }}</span></p>
          </td>
        </tr>
        <tr>
          <td colspan="8" class="clearfix">
            <p class="fl" style="width: 350px;">电子客票号码：<span class="value">{{= d.eticketNo }}</span></p>
            <p class="fl">验证码：<span class="value">{{= d.checkCode }}</span></p>
            <p class="fl clearfix" style="margin-left: 50px; width: 420px;">
              <span class="fl">提示信息：</span>
              <span class="value fl" style="width: 340px">{{= d.提示信息 }}</span>
            </p>
          </td>
          <td colspan="2">
            <p>保险费：<span class="value">{{= d.insurance }}</span></p>
          </td>
        </tr>
        <tr>
          <td colspan="10" class="clearfix">
            <p class="fl" style="width: 350px;">销售网点代号：<span class="value">{{= d.agentCode }}</span></p>
            <p class="fl">填开单位：<span class="value">{{= d.issuedBy }}</span></p>
            <p class="fr">填开日期：<span class="value">{{= d.issuedDate }}</span></p>
          </td>
        </tr>
        <tr>
          <td colspan="10" class="clearfix">
            <p class="fl" style="width: 50%;">购买方名称：<span class="value">{{= d.buyerName }}</span></p>
            <p class="fl">统一社会信用代码/纳税人识别号：<span class="value">{{= d.buyerId  }}</span></p>
          </td>
        </tr>
      </table>
    </div>
  `).render(payload);

            return html
        },
        genTmpl2(payload) {
            const html = layui.laytpl(`
    <div class="invoice-layout__wrap tmpl-2">
      <div class="invoice-layout__header">
        <h3 class="title">{{= d.title }}</h3>
        <div class="invoice-layout__header-content">
          <p style="margin-bottom: 20px;">发票号码：<span class="value">{{= d.invoiceNumber }}</span></p>
          <p>开票日期：<span class="value">{{= d.issueDate }}</span></p>
        </div>
      </div>

      <table class="invoice-layout__table">
        <tr>
          <th width="20" style="writing-mode: vertical-lr; letter-spacing: 4px;">购买方信息</th>
          <td>
            <p style="margin-bottom: 20px;">名称：<span class="value">{{= d.payerName }}</span></p>
            <p>统一社会信用代码/纳税人识别号：<span class="value">{{= d.payerId }}</span></p>
          </td>
          <th width="20" style="writing-mode: vertical-lr; letter-spacing: 4px;">销售方信息</th>
          <td>
            <p style="margin-bottom: 20px;">名称：<span class="value">{{= d.sellerName }}</span></p>
            <p>统一社会信用代码/纳税人识别号：<span class="value">{{= d.sellerId }}</span></p>
          </td>
        </tr>
        <tr>
          <td colspan="4" style="padding: 5px;">
            <table style="width: 100%; text-align: center">
              <tr class="project-item">
                <th width="180">项目名称</th>
                <th>规格型号</th>
                <th>单 位</th>
                <th>数 量</th>
                <th>单 价</th>
                <th>金 额</th>
                <th>税率/征收率</th>
                <th>税 额</th>
              </tr>
              {{#  layui.each(d.projectList, function(index, item) { }}
                <tr class="project-item">
                  <td><span class="value">{{= item.name }}</span></td>
                  <td><span class="value">{{= item.specification }}</span></td>
                  <td><span class="value">{{= item.unit }}</span></td>
                  <td><span class="value">{{= item.quantity }}</span></td>
                  <td><span class="value">{{= item.unitPrice }}</span></td>
                  <td><span class="value">{{= item.price }}</span></td>
                  <td><span class="value">{{= item.taxRate }}</span></td>
                  <td><span class="value">{{= item.tax }}</span></td>
                </tr>
              {{#  }); }}
              <tr height="50"></tr>
              <tr class="project-item">
                <td>合 计</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td><span class="value">¥{{= d.taxExclusiveTotalAmount }}</span></td>
                <td></td>
                <td><span class="value">¥{{= d.taxTotalAmount }}</span></td>
              </tr>  
            </table>  
          </td>
        </tr>
        <tr>
          <td colspan="2">价税合计（大写）</td>
          <td colspan="2">
            <span class="value fl">
              <svg t="1733797102200" class="icon cap-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="22068" width="200" height="200"><path d="M512 32c265.097 0 480 214.903 480 480S777.097 992 512 992 32 777.097 32 512 246.903 32 512 32z m0 41.74C269.955 73.74 73.74 269.954 73.74 512S269.954 950.26 512 950.26 950.26 754.046 950.26 512 754.046 73.74 512 73.74z" p-id="22069"></path><path d="M831.697 204.547c8.439-7.851 21.644-7.375 29.495 1.063 7.851 8.439 7.375 21.644-1.063 29.495L213.172 837.04c-8.438 7.851-21.643 7.375-29.495-1.063-7.85-8.439-7.375-21.644 1.064-29.495l646.956-601.934z" p-id="22070"></path><path d="M161.138 205.637c7.836-8.452 21.04-8.951 29.493-1.115l649.113 601.842c8.452 7.836 8.95 21.04 1.114 29.493-7.836 8.452-21.04 8.95-29.493 1.114L162.252 235.13c-8.452-7.837-8.95-21.041-1.114-29.493z" p-id="22071"></path></svg>
              {{= d['价税合计（大写）'] }}
            </span>
            <p class="fr">（小写）<span class="value">¥{{= d.taxInclusiveTotalAmount }}</span></p>
          </td>  
        </tr>
        <tr height="100">
          <th style="writing-mode: vertical-lr; letter-spacing: 4px;">备注</th>
          <td colspan="3"><span class="value">{{= d.remark }}</span></td>
        </tr>
      </table>
      <p style="padding: 20px;">开票人：<span class="value">{{= d.drawerName }}</span></p>
    </div>
  `)
                .render(payload)

            return html
        },
        genTmpl3(payload) {
            const html = layui.laytpl(`
    <div class="invoice-layout__wrap tmpl-3">
      <div class="invoice-layout__header">
        <h3 class="title">{{= d.title }}</h3>
      </div>
      
      <div class="invoice-layout__body">
        <div class="clearfix">
          <span class="fl"><strong style="font-weight: 700;">发票号码：</strong>{{= d.invoiceNumber }}</span>
          <span class="fr"><strong style="font-weight: 700;">开票日期：</strong>{{= d.issueDate }}</span>
        </div>
        <div class="train-intro__container clearfix">
          <div class="station depart fl" style="width: 20%">
            <p><span>{{= d.departureStation }}</span>站</p>
            <p>{{= d.departureStationPinyin }}</p>
          </div>
          <div class="train-no fl" style="width: 60%">
            <p>{{= d.trainNumber }}</p>
            <svg t="1733729790895" class="icon" viewBox="0 0 8533 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5785" xmlns:xlink="http://www.w3.org/1999/xlink" width="1666.6015625" height="200"><path d="M6656 682.666667V0l1877.333333 1024H0V682.666667h6656z" fill="#8a8a8a" p-id="5786"></path></svg>
          </div>
          <div class="station arrive fl" style="width: 20%">
            <p><span>{{= d.destinationStation }}</span>站</p>
            <p>{{= d.destinationStationPinyin }}</p>
          </div>
        </div>
        <div class="train-intro__cell clearfix" style="margin-bottom: 20px;">
          <p class="fl" style="width: 40%;">{{= d.departureDate }}&nbsp;&nbsp;{{= d.departureTime }}开</p>
          <p class="fl" style="width: 30%;">{{= d.carriage }}{{= d.seat }}</p>
          <p class="fl">{{= d.seatLevelTypeName }}</p>
        </div>
        <div class="train-intro__cell" style="margin-bottom: 30px;">
          <p><strong style="font-weight: 700;">票价：</strong><span style="font-size: 20px;">{{= d.totalAmount }}</span></p>
        </div>
        <div class="train-intro__cell clearfix" style="margin-bottom: 30px;">
          <p class="fl" style="width: 40%;">{{= d.idNumber }}</p>
          <p class="fl">{{= d.passengerName }}</p>
        </div>
        <div class="train-intro__cell">
          <p><strong style="font-weight: 700;">电子客票号：</strong>{{= d.eticketNumber }}</p>
        </div>
      </div>
      <div class="invoice-layout__footer">
        <div class="clearfix">
          <span class="fl"><strong style="font-weight: 700;">购买方名称：</strong>{{= d.buyerName }}</span>
          <span class="fr"><strong style="font-weight: 700;">统一社会信用代码：</strong>{{= d.buyerId }}</span>
        </div>

        <p class="tips">买票请到12306 发货请到95306<br />中国铁路祝您旅途愉快</p>
      </div>
    </div>
  `)
                .render(payload)

            return html
        },
        genTmpl4(payload) {
            const html = layui.laytpl(`
    <div class="invoice-layout__wrap tmpl-4">
      <div class="invoice-layout__header">
        <h3 class="title">{{= d.title }}</h3>
        <div class="invoice-layout__header-content">
          <p class="left">机器编号：<span class="value">{{= d.机器编号 }}</span></p>
          <div class="right">
            <p class="line-height-24"><span class="label">发票代码</span>：<span class="value">{{= d.发票代码 }}</span></p>
            <p class="line-height-24"><span class="label">发票号码</span>：<span class="value">{{= d.invoiceNumber }}</span></p>
            <p class="line-height-24"><span class="label">开票日期</span>：<span class="value">{{= d.issueDate }}</span></p>
            <p class="line-height-24"><span class="label">校验码</span>：<span class="value">{{= d.校验码 }}</span></p>
          </div>
        </div>
      </div>

      <table class="invoice-layout__table">
        <tr>
          <th width="20" style="writing-mode: vertical-lr; letter-spacing: 4px;">购买方</th>
          <td>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">名称</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.payerName }}</span>
            </div>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">纳税人识别号</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.payerId }}</span>
            </div>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">地 址、电 话</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.PayerAddressPhone }}</span>
            </div>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">开户行及账号</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.PayerBankAccount }}</span>
            </div>  
          </td>
          <th width="20" style="writing-mode: vertical-lr; letter-spacing: 4px;">密码区</th>
          <td><span class="value">{{= d.密码区 }}</span></td>
        </tr>
        <tr>
          <td colspan="4" style="padding: 0;">
            <table style="width: 100%; text-align: center">
              <tr class="project-item">
                <th width="180" class="pt-5">项目名称</th>
                <th class="pt-5">规格型号</th>
                <th class="pt-5">单 位</th>
                <th class="pt-5">数 量</th>
                <th class="pt-5">单 价</th>
                <th class="pt-5">金 额</th>
                <th class="pt-5">税率</th>
                <th class="pt-5">税 额</th>
              </tr>
              {{#  layui.each(d.projectList, function(index, item) { }}
                <tr class="project-item">
                  <td><span class="value">{{= item.name }}</span></td>
                  <td><span class="value">{{= item.specification }}</span></td>
                  <td><span class="value">{{= item.unit }}</span></td>
                  <td><span class="value">{{= item.quantity }}</span></td>
                  <td><span class="value">{{= item.unitPrice }}</span></td>
                  <td><span class="value">{{= item.price }}</span></td>
                  <td><span class="value">{{= item.taxRate }}</span></td>
                  <td><span class="value">{{= item.tax }}</span></td>
                </tr>
              {{#  }); }}
               {{#  layui.each([1, 2], function(_, __) { }}
                <tr>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
              {{#  }); }}
              <tr class="project-item">
                <td class="pb-5">合 计</td>
                <td class="pb-5"></td>
                <td class="pb-5"></td>
                <td class="pb-5"></td>
                <td class="pb-5"></td>
                <td class="pb-5"><span class="value">¥{{= d.taxExclusiveTotalAmount }}</span></td>
                <td class="pb-5"></td>
                <td class="pb-5"><span class="value">¥{{= d.taxTotalAmount }}</span></td>
              </tr>  
            </table>  
          </td>
        </tr>
        <tr>
          <td colspan="2">价税合计（大写）</td>
          <td colspan="2" class="clearfix">
            <span class="value fl">
              <svg t="1733797102200" class="icon cap-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="22068" width="200" height="200"><path d="M512 32c265.097 0 480 214.903 480 480S777.097 992 512 992 32 777.097 32 512 246.903 32 512 32z m0 41.74C269.955 73.74 73.74 269.954 73.74 512S269.954 950.26 512 950.26 950.26 754.046 950.26 512 754.046 73.74 512 73.74z" p-id="22069"></path><path d="M831.697 204.547c8.439-7.851 21.644-7.375 29.495 1.063 7.851 8.439 7.375 21.644-1.063 29.495L213.172 837.04c-8.438 7.851-21.643 7.375-29.495-1.063-7.85-8.439-7.375-21.644 1.064-29.495l646.956-601.934z" p-id="22070"></path><path d="M161.138 205.637c7.836-8.452 21.04-8.951 29.493-1.115l649.113 601.842c8.452 7.836 8.95 21.04 1.114 29.493-7.836 8.452-21.04 8.95-29.493 1.114L162.252 235.13c-8.452-7.837-8.95-21.041-1.114-29.493z" p-id="22071"></path></svg>
              {{= d['价税合计（大写）'] }}
            </span>
            <p class="fr" style="line-height: 20px">（小写）<span class="value fr">¥{{= d.taxInclusiveTotalAmount}}</span></p>
          </td>
        </tr>
        <tr>
          <th width="20" style="writing-mode: vertical-lr; letter-spacing: 4px;">销售方</th>
          <td>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">名称</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.sellerName }}</span>
            </div>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">纳税人识别号</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.sellerId }}</span>
            </div>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">地 址、电 话</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.sellerAddressPhone }}</span>
            </div>
            <div class="line-height-24 clearfix">
              <p class="fl"><span class="label">开户行及账号</span>：</p>
              <span class="value fl" style="width: calc(100% - 14px - 100px)">{{= d.sellerBankAccount }}</span>
            </div>  
          </td>
          <th width="20" style="writing-mode: vertical-lr; letter-spacing: 4px;">备注</th>
          <td><span class="value">{{= d.remark }}</span></td>
        </tr>
      </table>
      <div class="clearfix" style="padding: 20px;">
        <p class="fl" style="width: 25%;">收款人：<span class="value">{{= d.收款人 }}</span></p>
        <p class="fl" style="width: 25%;">复核：<span class="value">{{= d.复核 }}</span></p>
        <p class="fl" style="width: 25%;">开票人：<span class="value">{{= d.drawerName }}</span></p>
      </div>
    </div>
  `)
                .render(payload)

            return html
        }
    }

    function doOpen(request) {
        //先获取发票详情
        let payload;
        $.ajax({
            url: setter.baseConfig.apiHost + '/api/myinvoice/getinvoicedetail' //实际使用请改成服务端真实接口
            , type: 'post'
            , async: false //同步请求
            , contentType: "application/json"
            , data: JSON.stringify(request)
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
            }
            , success: function (res) {
                if (res.errorCode != '00000') {
                    return;
                }

                payload = res.data;
            }
        });

        const map = {
            3: { title: '电子发票（航空运输电子客票行程单）', tmplType: 1, response: 'flightItineraryInfo' },
            1: { title: '电子发票（普通发票）', tmplType: 2, response: 'vatInvoiceInfo' },
            2: { title: '电子发票（增值税专用发票）', tmplType: 2, response: 'vatInvoiceInfo' },
            4: { title: '电子发票（铁路电子客票）', tmplType: 3, response: 'railwayTicketInfo' },
            5: { title: '增值税电子普通发票', tmplType: 4, response: 'vatInvoiceInfo' },
            6: { title: '增值税电子专用发票', tmplType: 4, response: 'vatInvoiceInfo' }
        }

        const item = map[+payload.billType]
        if (!item) return
        // 伪造数据start
        //payload = fakeDataMap[item.tmplType]
        // 伪造数据end

        const result = payload[item.response];
        result.title = item.title;
        //console.log(result);
        const tmpl = templateHelper['genTmpl' + item.tmplType](result)
        const htmlString = layui.laytpl(`
            <div class="preview-invoice__dialog">
              ${tmpl}
            </div>
            <button class="preview-file__btn" onclick="previewOriginalFile('{{= d.originalUrl }}')">查看源文件</button>
          `)
            .render({
                originalUrl: payload.sourceFilePath
            });

        // 在此处输入 layer 的任意代码
        layer.open({
            type: 1, // page 层类型
            area: ['auto', 'auto'],
            title: false, // 不显示标题栏
            shade: 0.6, // 遮罩透明度
            shadeClose: true, // 点击遮罩区域，关闭弹层
            anim: 5, // 0-6 的动画形式，-1 不开启
            closeBtn: 2, //关闭图标风格二
            isOutAnim: false,
            content: htmlString
        });
    }

    window.previewOriginalFile = function (url) {
        window.open(url, '_blank');
    }
  
  
  
  //退出
  admin.events.logout = function(){
    //执行退出接口
    admin.req({
      url: './res/json/user/logout.js'
      ,type: 'get'
      ,data: {}
      ,done: function(res){ //这里要说明一下：done 是只有 response 的 code 正常才会执行。而 succese 则是只要 http 为 200 就会执行
        
        //清空本地记录的 token，并跳转到登入页
        admin.exit();
      }
    });
  };

  
  //对外暴露的接口
    exports('common', {
        msg: 'hello world',
        test: function () {
            layer.msg('1111');
        },
        doOpen,

    });
});